<template>
  <view class="container">
    <!-- 顶部标题栏 -->
    <view class="header">
        <view class="header-content">
          <!-- 返回箭头 - 黑色尖括号样式 -->
          <view class="back-arrow" @click="goBack">
            <text class="arrow-icon">〈</text>
          </view>
          <!-- 标题文字 - 黑色无衬线字体 -->
          <text class="title">日行一善</text>
        </view>
    </view>

    <!-- 导航标签 -->
    <view class="tabs">
      <text 
        :class="['tab', activeTab === 'makeWish' ? 'active-tab' : '']"
        @click="activeTab = 'makeWish'">今日善举</text>
      <text 
        :class="['tab', activeTab === 'goodSquare' ? 'active-tab' : '']"
        @click="activeTab = 'goodSquare'">善举广场</text>
    </view>

    <!-- 善举发布页面 -->
    <view v-if="activeTab === 'makeWish'" class="good-page">
      <text class="slogan">日行一善·积福之始</text>
      
      <!-- 善举标题 -->
      <view class="form-group">
        <text class="label">善举标题：</text>
            <input 
              class="good-title-input" 
              placeholder="请输入" 
              v-model="dailyGoodTitle" 
            />
        </view>
      
        <!-- 善举时间 -->
        <view class="form-group">
          <text class="label">善举时间：</text>
          <view class="time-picker-group">
            <!-- 日期选择 -->
            <picker 
              mode="date" 
              :value="currentDate" 
              @change="bindDateChange"
              fields="day">
              <view class="picker time-picker">{{ currentDate || '选择日期' }}</view>
            </picker>
            
            <!-- 时间选择 -->
            <picker 
              mode="time" 
              :value="currentTime" 
              @change="bindTimeChange">
              <view class="picker time-picker">{{ currentTime || '选择时间' }}</view>
            </picker>
          </view>
        </view>
      
        <!-- 善举记录 -->
        <view class="good-input-container">
            <textarea 
              class="good-input" 
              placeholder="请输入" 
              v-model=" dailyGoodContent"
              maxlength="300"
            />
            <text class="char-count">{{ dailyGoodContent.length }}/300</text>
        </view>
      
        <!-- 图片上传 -->
        <view class="upload-container">
          <button class="upload-btn">上传一张图片（选填）</button>
        </view>

        <!-- 显示选项 -->
        <view class="visibility">
            <text class="visibility-label">在善举广场显示：</text>
            <view class="display-options">
                <text 
                  :class="['display-option', showInSquare ? 'selected' : '']"
                  @click="showInSquare = true"
                >显示</text>
                <text 
                  :class="['display-option', !showInSquare ? 'selected' : '']"
                  @click="showInSquare = false"
                >不显示</text>
              </view>
            </view>

          <!-- 提交按钮 -->
          <button class="submit-btn" @click="submitWish">发布善举</button>
    </view>

    <!-- 善举广场页面 -->
    <view v-if="activeTab === 'goodSquare'" class="square-page">
      <scroll-view class="good-list" scroll-y>
        <view v-for="(dailyGood, index) in dailyGoodList" :key="index" class="good-card">
          <!-- 用户信息 -->
          <view class="good-header">
            <!-- <text class="username">{{ dailyGood.trueName }}：</text> -->
            <text class="good-time">{{ dailyGood.doTime }}</text>
          </view>
          
          <!-- 善举内容 -->
          <text class="good-content">{{ dailyGood.content }}</text>
          
          <!-- 点赞区域 -->
          <view class="good-footer">
              <text class="support-count">已获得{{ dailyGood.likeCount }}点赞</text>
              <button class="support-btn" @click="supportWish(index)">为TA点赞</button>
            </view>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script setup>
import { computed, ref, onMounted } from 'vue';
import { useDailyGoodStore } from '@/stores/dailyGood';
import { useUserStore } from '@/stores/user';
import { redirect, switchTab } from '/utils/index.ts';
import { pageLink } from '/constants/link.ts';

const userStore = useUserStore();
const dailyGoodStore = useDailyGoodStore();
// 处理后的数据列表
const dailyGoodList = computed(() => {
  if (!dailyGoodStore.dailyGoodList?.rows) return []
  
  return dailyGoodStore.dailyGoodList.rows.map(item => ({
    ...item,
    doTime: item.doTime,
    title: item.title || '',
    content: item.content || '',
    trueName: item.trueName || ''
  }))
})

onMounted(async () => {
  await dailyGoodStore.list()
})

const formatDate = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}`;
};

// 用户信息
const userInfo = computed(() => userStore.userInfo || '');

// 善举信息
const dailyGoodTitle = ref('');
const dailyGoodContent = ref('');
const showInSquare = ref(true);
const activeTab = ref('makeWish');

// 初始化当前日期和时间
const currentDate = ref('')
const currentTime = ref('')
const dailyGoodTime = ref('')

// 设置默认值为当前日期和时间
const setDefaultDateTime = () => {
  const now = new Date()
  
  // 格式化日期 (YYYY-MM-DD)
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  currentDate.value = `${year}-${month}-${day}`
  
  // 格式化时间 (HH:mm)
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  currentTime.value = `${hours}:${minutes}`
  
  // 拼接完整时间 (YYYY-MM-DD HH:mm:00)
  dailyGoodTime.value = `${currentDate.value} ${currentTime.value}:00`
}

// 日期变化处理
const bindDateChange = (e) => {
  currentDate.value = e.detail.value
  dailyGoodTime.value = `${currentDate.value} ${currentTime.value}:00`
}

// 时间变化处理
const bindTimeChange = (e) => {
  currentTime.value = e.detail.value
  dailyGoodTime.value = `${currentDate.value} ${currentTime.value}:00`
}

// 组件挂载时设置默认时间
onMounted(() => {
  setDefaultDateTime()
})

// 提交善举
const submitWish = async () => {
  if (dailyGoodTitle.value.trim() === '') {
    uni.showToast({ title: '请输入善举标题', icon: 'none' });
    return;
  }
  
  if (dailyGoodTime.value.trim() === '') {
    uni.showToast({ title: '请选择善举时间', icon: 'none' });
    return;
  }
  
  if (dailyGoodContent.value.trim() === '') {
    uni.showToast({ title: '请输入善举记录', icon: 'none' });
    return;
  }
  
  if (dailyGoodContent.value.length > 300) {
    uni.showToast({ title: '最多输入300字符', icon: 'none' });
    return;
  }

  try {
    await dailyGoodStore.addOrModify({
      title: dailyGoodTitle.value,
      doTime: dailyGoodTime.value,
      content: dailyGoodContent.value,
      display: true,
    });
    
    uni.showToast({
      title: '善举已发布，积善之家必有余庆',
      icon: 'none',
      duration: 1500,
      success: () => {
        setTimeout(() => {
          switchTab(pageLink.blessings);
        }, 1500);
      }
    });
  } catch (error) {
    // uni.showToast({ title: '提交失败，请重试', icon: 'none' });
    // uni.showToast({
    //   title: '善举已发布，积善之家必有余庆',
    //   icon: 'none',
    //   duration: 1500,
    //   success: () => {
    //     setTimeout(() => {
    //       switchTab(pageLink.blessings);
    //     }, 1500);
    //   }
    // });
  }
};

// 返回功能
const goBack = () => {
  switchTab(pageLink.blessings);
};

// 点赞善举
const supportWish = (index) => {
  uni.showToast({
    title: '已点赞',
    icon: 'success'
  });
};
</script>

<style>
/* 通用样式 */
.container {
  background-color: #FFFCF1;
  min-height: 100vh;
  padding: 20rpx;
}

/* 导航栏 */
.header {
  height: 88rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  border-bottom: 1rpx solid #F5F5F5;
  margin-top: 48rpx;
}

.header-content {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  padding: 0 30rpx;
  box-sizing: border-box;
}

.back-arrow {
  width: 80rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-arrow:active {
  background-color: rgba(0,0,0,0.1);
}

.arrow-icon {
  font-size: 38rpx;
  color: #000000;
  transform: scale(1.2);
}

.title {
  flex: 1;
  text-align: center;
  font-size: 36rpx;
  color: #000000;
  font-weight: 500;
  margin-left: -60rpx;
}

/* 导航标签 */
.tabs {
  display: flex;
  border-bottom: 2rpx solid #eee;
  margin-bottom: 30rpx;
}

.tab {
  flex: 1;
  text-align: center;
  padding: 20rpx;
  font-size: 32rpx;
  color: #999;
}

.active-tab {
  color: #FF4D4F;
  position: relative;
}

.active-tab::after {
  content: '';
  position: absolute;
  bottom: -2rpx;
  left: 50%;
  transform: translateX(-50%);
  width: 80rpx;
  height: 4rpx;
  background-color: #FF4D4F;
}
/* 时间选择器组 */
.time-picker-group {
  flex: 1;
  display: flex;
  background-color: #F5F5F5;
  border-radius: 8rpx;
  overflow: hidden; /* 确保圆角效果 */
}

/* 单个时间选择器 */
.time-picker {
  flex: 1;
  text-align: center;
  padding: 16rpx 0;
  position: relative;
}

/* 移除picker之间的间隔线 */
.time-picker:not(:last-child)::after {
  content: "";
  position: absolute;
  right: 0;
  top: 10rpx;
  bottom: 10rpx;
  width: 1rpx;
  background-color: #ddd;
}
/* 表单样式 */
.form-group {
  margin-bottom: 30rpx;
  display: flex;
  align-items: center;
  min-height: 60rpx;
}

.label {
  font-size: 28rpx;
  color: #444;
  margin-right: 20rpx;
  width: 140rpx;
}

/* 输入框和选择器统一样式 */
.good-title-input,
.picker {
  flex: 1;
  height: 60rpx;
  font-size: 28rpx;
  color: #333;
  padding: 16rpx 20rpx;
  border-radius: 8rpx;
  background-color: #F5F5F5;
  border: none;
  box-sizing: border-box;
}

/* 善举记录输入区 */
.good-input-container {
  position: relative;
  margin-bottom: 30rpx;
}

.good-input {
  width: 100%;
  height: 200rpx;
  border: 1rpx solid #EEEEEE;
  border-radius: 8rpx;
  padding: 20rpx;
  font-size: 28rpx;
  background: #FFFFFF;
}

.char-count {
  position: absolute;
  right: 20rpx;
  bottom: 10rpx;
  font-size: 24rpx;
  color: #999;
}

/* 上传按钮 */
.upload-container {
  margin-bottom: 30rpx;
}

.upload-btn {
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
  background-color: #F5F5F5;
  color: #666;
  font-size: 28rpx;
  border-radius: 8rpx;
  border: none;
}

/* 显示选项 */
.visibility {
  display: flex;
  align-items: center;
  margin-bottom: 30rpx;
}

.visibility-label {
  font-size: 28rpx;
  color: #444;
  margin-right: 20rpx;
}

.display-options {
  display: flex;
}

.display-option {
  padding: 8rpx 24rpx;
  margin-right: 16rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
  color: #333;
  background-color: #F5F5F5;
  box-shadow: 0 2rpx 6rpx rgba(0,0,0,0.1);
}

.display-option.selected {
  background-color: #FFFFFF;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.15);
  font-weight: bold;
}

/* 页面样式 */
.good-page {
  background: #FFFFFF;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.05);
}

.slogan {
  display: block;
  text-align: center;
  font-size: 36rpx;
  color: #FF4D4F;
  font-weight: bold;
  margin-bottom: 40rpx;
}

.submit-btn {
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
  background-color: #FF4D4F;
  color: white;
  font-size: 32rpx;
  border-radius: 40rpx;
  border: none;
  margin-top: 20rpx;
}

/* 善举广场 */
.square-page {
  padding-bottom: 40rpx;
}

.good-list {
  height: calc(100vh - 240rpx);
}

.good-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.05);
}

.good-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20rpx;
}

.username {
  font-weight: bold;
  font-size: 34rpx;
}

.good-time {
  color: #999;
  font-size: 28rpx;
}

.good-content {
  font-size: 36rpx;
  line-height: 1.5;
  margin-bottom: 30rpx;
  white-space: pre-wrap;
}

.good-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-top: 1rpx solid #F5F5F5;
  padding-top: 20rpx;
  margin-top: 20rpx;
}

.support-count {
  color: #999999;
  font-size: 28rpx;
}

.support-btn {
  background-color: #FF4D4F;
  color: white;
  font-size: 28rpx;
  padding: 0 30rpx;
  height: 60rpx;
  line-height: 60rpx;
  border-radius: 30rpx;
  border: none;
  box-shadow: 0 2rpx 6rpx rgba(0,0,0,0.1);
}

.support-btn:active {
  opacity: 0.9;
  transform: scale(0.98);
}
</style>